package com.yami.shop.listener;

import com.yami.shop.bean.event.DelRongEvent;
import com.yami.shop.bean.event.DismissGroupEvent;
import com.yami.shop.bean.event.RegisterRongEvent;
import com.yami.shop.common.exception.YamiShopBindException;
import com.yami.shop.service.impl.RongYunGroupServiceImpl;
import com.yami.shop.service.impl.RongYunUserServiceImpl;
import com.yami.shop.vo.group.GroupVo;
import com.yami.shop.vo.group.UserIdVo;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;

import java.util.Arrays;

@Slf4j
@Component("userGroupListener")
@AllArgsConstructor
public class UserGroupListener {

    private final RongYunGroupServiceImpl groupService;

    private final RongYunUserServiceImpl rongYunUserService;

    @EventListener(DismissGroupEvent.class)
    public void dismissGroup(DismissGroupEvent event){
        UserIdVo userIdVo = UserIdVo.builder().id(event.getCreatorUserId()).build();
        GroupVo groupVo = GroupVo.builder().groupId(event.getGroupId().toString()).creatorUserId(event.getCreatorUserId())
                .groupName(event.getGroupName()).users(Arrays.asList(userIdVo)).build();
        try {
            groupService.dismiss(groupVo);
            log.info("===解散群完成===");
        } catch (Exception e) {
            log.error("解散群异常：", e.getMessage());
        }
    }


    @EventListener(RegisterRongEvent.class)
    public void registerRongReq(RegisterRongEvent event){
        try {
//            RegisterRongReqDTO registerRongReqDTO = BeanUtil.copyProperties(event, RegisterRongReqDTO.class);
//            rongYunUserService.userRegister(registerRongReqDTO);
        }catch (Exception e){
            throw new YamiShopBindException("yami.user.rongyun.error");
        }

    }

    @EventListener(DelRongEvent.class)
    public void abandonRongReq(DelRongEvent event){
        try {
            rongYunUserService.abandon(event.getUserId());
        }catch (Exception e){
            log.error("融云用户注销异常，" + e.getMessage());
        }

    }


}
